//
//  UserAccount.swift
//  Weibo
//
//  Created by zxy on 2018/12/6.
//  Copyright © 2018 zxy. All rights reserved.
//

import UIKit
import YYModel
class UserAccount: NSObject {
    /*定义属性，用来保存登录成功的信息*/
    @objc var access_token: String?
    
    //access_token过期时间
    @objc var expireDate:Date?
    
    //access_token有效期，单位s
    @objc var expires_in: NSNumber?{
        didSet{//expires_in赋值了就会走这个方法，相当于oc中的重写属性的set方法
            expireDate = Date(timeIntervalSinceNow: expires_in!.doubleValue)
            print(expireDate as Any)
        }
    }
   @objc var uid: String?
    
    
    
//    init(dict: [String: Any]) {
//        super.init()
//        //dict:通过传入字典里的key，来给对应的key设置值
//        //必须重写forUndefinedKey方法，因为dict里面还有其它的key，没有在这里声明，会导致程序崩溃，提示找不到key
//        setValuesForKeys(dict)
//    }
    /*
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
    }
    
    //定义一个类方法，返回用户是否登录成功标志
    class func isLoginSuccess() -> Bool{
        return UserAccount.readUserAccountInfo() != nil
    }
    
    /*保存自定义对象，只能用数据库或者归档*/
    //归档数据
    func savaUserAccountInfo(){
        //将数据保存到cache
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
        
    }
    
    //保存已经接归档数据，如果有数据就不接归档，优化性能
    static var account:UserAccount?

    //解归档
    class func readUserAccountInfo() ->UserAccount?{
        if account != nil{
            return account
        }
        
        //将数据保存到cache
      account = NSKeyedUnarchiver.unarchiveObject(withFile: "account.plist".cacheDir()) as? UserAccount
        return account
    }
    
    //将对象写入到文件中
    func encode(with aCoder: NSCoder){
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expireDate, forKey: "expireDate")
    }
    
    //从文件中读取对象
    required init?(coder aDecoder: NSCoder){
       access_token = aDecoder.decodeObject(forKey: "access_token") as? String
       expires_in = aDecoder.decodeObject(forKey: "expires_in") as? NSNumber
       uid = aDecoder.decodeObject(forKey: "uid") as? String
       expireDate = aDecoder.decodeObject(forKey: "expireDate") as? Date
    }
    */
    override var description: String{
        return yy_modelDescription()
    }
}
